package com.ccteam.fluidmusic.ui.playlist

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.setFragmentResult
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.bumptech.glide.Glide
import com.ccteam.fluidmusic.R
import com.ccteam.fluidmusic.databinding.FragmentPlaylistSheetEditBinding
import com.ccteam.fluidmusic.utils.EventObserver
import com.ccteam.fluidmusic.view.bean.LoadMessage
import com.ccteam.fluidmusic.widget.SNACKBAR_PLAY_BAR
import com.ccteam.fluidmusic.widget.snackbar
import com.ccteam.fluidmusic.ui.playlist.select.AddOnlineMediaFragment.Companion.RESULT_PLAYLIST_TYPE_KEY
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author Xiaoc
 * @since 2021/3/17
 *
 * 歌单编辑界面Fragment
 */
@AndroidEntryPoint
class PlaylistSheetEditFragment: Fragment() {

    private var _binding: FragmentPlaylistSheetEditBinding? = null
    private val binding: FragmentPlaylistSheetEditBinding get() = _binding!!

    private val playlistSheetEditViewModel by viewModels<PlaylistSheetEditViewModel>()

    /**
     * 选择图片的内容
     * 选择完手机中的图片后，将其存储到ViewModel中
     */
    private val selectImage = registerForActivityResult(ActivityResultContracts.GetContent()) { imageUri ->
        imageUri?.let {
            playlistSheetEditViewModel.setPlaylistSheetImgUrl(it.toString())
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentPlaylistSheetEditBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        binding.ivPlaylistSheetPhoto.setOnClickListener {
            selectImage.launch("image/*")
        }

        binding.toolbarEditPlaylistSheet.setNavigationOnClickListener {
            findNavController().navigateUp()
        }

        playlistSheetEditViewModel.editPlaylistSheet.observe(viewLifecycleOwner, {
            updateUI(it)
        })

        playlistSheetEditViewModel.uploadPhotoStatus.observe(viewLifecycleOwner, EventObserver{
            updatePhotoProgress(it is LoadMessage.Loading)
            when (it) {
                is LoadMessage.Success -> {
                    view.snackbar(R.string.description_upload_head_photo_success).show()
                }
                is LoadMessage.Error -> {
                    view.snackbar(it.errorMessage.description.toString()).show()
                }
                else -> {}
            }
        })

        playlistSheetEditViewModel.loadMessage.observe(viewLifecycleOwner, EventObserver{
            updateStatus(it is LoadMessage.Loading)
            if(it is LoadMessage.Success){
                view.snackbar("修改歌单信息成功", SNACKBAR_PLAY_BAR).show()
                setFragmentResult(RESULT_PLAYLIST_TYPE_KEY, bundleOf(
                    RESULT_PLAYLIST_TYPE_KEY to true
                ))
                findNavController().navigateUp()
            } else if(it is LoadMessage.Error){
                view.snackbar("修改歌单信息失败：${it.errorMessage.description}", SNACKBAR_PLAY_BAR).show()
            }
        })

        binding.btnEditPlaylistSheet.setProgressButtonOnClickListener {
            playlistSheetEditViewModel.editPlaylistSheetInfo(
                binding.editPlaylistSheetName.editText?.text.toString(),
                binding.editPlaylistSheetIntroduction.editText?.text.toString()
            )
        }
    }

    /**
     * 当正在提交歌单中，不允许按钮多次点击，并设置按钮为加载状态
     */
    private fun updateStatus(isLoading: Boolean) = with(binding){
        editPlaylistSheetName.isEnabled = !isLoading
        editPlaylistSheetIntroduction.isEnabled = !isLoading
        ivPlaylistSheetPhoto.isEnabled = !isLoading
        btnEditPlaylistSheet.setLoading(isLoading)
    }


    private fun updateUI(playlistInfo: PlaylistSheetEditInfo) = with(binding){
        editPlaylistSheetName.editText?.setText(playlistInfo.playlistName)
        editPlaylistSheetIntroduction.editText?.setText(playlistInfo.playlistIntroduction)
        Glide.with(ivPlaylistSheetPhoto)
            .load(playlistInfo.playlistImgUrl)
            .placeholder(R.drawable.img_default_album)
            .into(ivPlaylistSheetPhoto)
    }

    /**
     * 如果图片正在上传，则不允许其点击下方的内容，展示一层蒙版并禁止控件使用
     */
    private fun updatePhotoProgress(isLoading: Boolean) = with(binding){
        containerPhotoProgress.isVisible = isLoading
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}